package org.minbox.framework.mantool.core;

import org.minbox.framework.mantool.core.support.page.PageRequest;
import org.minbox.framework.mantool.core.support.page.PageResponse;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Page 分页 Utils 函数
 *
 * @author 就眠仪式
 * */
public class PageUtil {

    /**
     * 内存分页
     *
     * @param records  待分页的数据
     * @param pageIndex  当前页码
     * @param pageSize 每页显示的条数
     * @return 分页之后的数据
     */
    public static <T> List<T> pagination(List<T> records, int pageIndex, int pageSize) {
        if (records==null) {
            return Collections.emptyList();
        }
        int totalCount = records.size();
        int remainder = totalCount % pageSize;
        int pageCount = (remainder > 0) ? totalCount/pageSize + 1 : totalCount/pageSize;
        if (remainder == 0) {
            return records.stream().skip((pageIndex - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        } else {
            if (pageIndex == pageCount) {
                return records.stream().skip((pageIndex - 1) * pageSize).limit(totalCount).collect(Collectors.toList());
            } else {
                return records.stream().skip((pageIndex - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
            }
        }
    }

    /**
     * 内存分页
     *
     * @param records  待分页的数据
     * @param pageRequest  封装参数
     * @return 分页之后的数据
     */
    public static <T> PageResponse<T> pagination(List<T> records, PageRequest pageRequest){
        List<T> ts = pagination(records, pageRequest.getPageIndex(), pageRequest.getPageSize());
        PageResponse<T> response = new PageResponse<>();
        response.setData(ts);
        response.setIndex(pageRequest.getPageIndex());
        response.setTotal(records.size());
        return response;
    }
}
